
import Custom from './custom'
import Decision from './decision'
import End from './end'
import Fork from './fork'
import Join from './join'
import Start from './start'
import Task from './task'
import Transtion from './transition'
import SubProcess from './subProcess'
import WfSubProcess from './wfSubProcess'

/**
 * 组件注册
 */
class WorkingFlowerElement {
    static pluginName = 'workingFlowerElement';

    constructor(data: any) {
        data.lf.register(Custom)
        data.lf.register(Decision)
        data.lf.register(End)
        data.lf.register(Fork)
        data.lf.register(Join)
        data.lf.register(Start)
        data.lf.register(Task)
        data.lf.register(Transtion)
        data.lf.register(SubProcess)
        data.lf.register(WfSubProcess)
    }
}

/**
 * WorkingFlower 数据转换器
 */
class WorkingFlowerAdapter {
    static pluginName = 'workingFlowerAdapter';
    constructor({ lf }: { lf: any }) {
        //数据输入转换
        lf.adapterIn = (userData: any) => {
            userData = userData.json ? userData.json : userData
            // 对入参数据进行简单处理
            userData = userData.json ? userData.json : userData
            // 对入参数据进行简单处理
            if (userData.nodes) {
                userData.nodes.forEach((node: any) => {
                    if (typeof node.properties.field === 'object') {
                        node.properties.field = JSON.stringify(node.properties.field)
                    }
                })
            }
            // 将流程扩展属性绑定给lf图模型对象
            lf.graphModel.name = userData.name ?? ''
            lf.graphModel.display_name = userData.display_name ?? ''
            lf.graphModel.expire_time = userData.expire_time ?? ''
            lf.graphModel.instance_url = userData.instance_url ?? ''
            lf.graphModel.instance_no_class = userData.instance_no_class ?? ''
            return userData
        }
        //数据输出转换
        lf.adapterOut = (logicFlowData: any) => {
            const graphData = {
                name: lf.graphModel.name,
                display_name: lf.graphModel.display_name,
                expire_time: lf.graphModel.expire_time,
                instance_url: lf.graphModel.instance_url,
                instance_no_class: lf.graphModel.instance_no_class,
                ...logicFlowData
            }
            Object.keys(graphData).forEach((key: string) => {
                // 删除undefined的值
                if (graphData[key] === undefined) {
                    delete graphData[key]
                }
            })
            // 处理一下loyat数据-stringjson==>obj
            graphData.nodes.forEach((node: any) => {
                if (node.type === 'ingenious:task' && node.properties.field) {
                    // console.log(node)
                    // node.properties.field = JSON.parse(node.properties.field)
                }
            })
            return graphData
        }
    }
}

export {
    WorkingFlowerElement,
    WorkingFlowerAdapter
}
